package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.events.Event;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /*
    * 发送手机短信验证码
    *   1、获取手机号（前端传）
    *   2、生成随机验证码
    *   3、调用阿里云短信服务api完成发送短信
    *   4、把验证码存储起来（session）
    * */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        //判个空
        if (StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();  //工具类
            System.out.println(code);

//            SMSUtils.sendMessage("瑞吉外卖","11",phone,code);

//            session.setAttribute(phone,code);
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.success("验证码发送成功");
        }
        return R.error("短信发送失败");
    }

    /*
        移动端登录验证
        1、获取手机号和验证码进行对比
        2、如果数据库中没有此信息，就自动完成注册
    * */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        //取前端输入的的手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //取session中的验证码
//        Object codeInSession = session.getAttribute(phone);
        Object codeInSession = redisTemplate.opsForValue().get(phone);


        if (codeInSession != null && codeInSession.equals(code)){
            //登录成功
            //判断用户是否存在，如果不存在自动注册
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //select count(*) from user where phone = (前端传过来的手机号)
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            User userGetOne = userService.getOne(userLambdaQueryWrapper);
            if (userGetOne == null){
                //新用户，添加到数据库
                User user1 = new User();
                user1.setPhone(phone);
                userService.save(user1);
            }
            session.setAttribute("user", userGetOne.getId());
            redisTemplate.delete(phone);  //登录成功就删除缓存中验证码
            return R.success(userGetOne);
        }
        //登录失败
        return R.error("登录失败");
    }
}
